<template>
  <div class="wrapper">
    <!-- 顶部导航 -->
    <header>
      <i class="fa fa-arrow-left" @click="goBack"></i>
      <div class="title">我的收货地址</div>
      <div class="placeholder"></div>
    </header>

    <!-- 地址列表 -->
    <div class="address-list" v-if="addressList.length > 0">
      <div 
        class="address-item" 
        v-for="address in addressList" 
        :key="address.daId"
        @click="selectAddress(address)"
      >
        <div class="info">
          <div class="user-info">
            <span class="name">{{ address.contactName }}</span>
            <span class="gender">{{ address.contactSex === 1 ? '先生' : '女士' }}</span>
            <span class="phone">{{ address.contactTel }}</span>
          </div>
          <div class="address-detail">
            {{ address.address }}
          </div>
        </div>
        <div class="operations">
          <div class="edit" @click.stop="editAddress(address)">
            <i class="fa fa-edit"></i>
            <span>编辑</span>
          </div>
          <div class="delete" @click.stop="deleteAddressHandler(address)">
            <i class="fa fa-trash"></i>
            <span>删除</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <i class="fa fa-address-card-o"></i>
      <p>暂无收货地址</p>
    </div>

    <!-- 添加新地址按钮 -->
    <div class="add-address" @click="showAddressForm = true">
      + 新增收货地址
    </div>

    <!-- 地址表单弹窗 -->
    <el-dialog
      v-model="showAddressForm"
      :title="currentAddress ? '编辑地址' : '新增地址'"
      width="90%"
    >
      <el-form :model="addressForm" label-width="80px">
        <el-form-item label="收货人">
          <el-input v-model="addressForm.contactName" placeholder="请输入收货人姓名"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addressForm.contactSex">
            <el-radio :value="1">先生</el-radio>
            <el-radio :value="0">女士</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="addressForm.contactTel" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input
            v-model="addressForm.address"
            type="textarea"
            placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddressForm = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAddressList, addAddress, updateAddress, deleteAddress } from '../api/address'
import { useUserInfoStore } from '../stores/user';

const router = useRouter()
const route = useRoute()
const addressList = ref([])
const showAddressForm = ref(false)
const currentAddress = ref(null)
const isFromCart = ref(route.query.from === 'cart')
const userInfoStore = useUserInfoStore();

// 地址表单数据
const addressForm = ref({
  contactName: '',
  contactSex: 1,
  contactTel: '',
  address: '',
  userId: userInfoStore.userInfo.id // 这里需要从登录用户信息中获取
})

// 获取地址列表
const loadAddressList = async () => {
  try {
    const res = await getAddressList(addressForm.value.userId)
    if (res.code === 0) {
      addressList.value = res.data
    } else {
      ElMessage.error(res.message || '获取地址列表失败')
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 保存地址
const saveAddress = async () => {
  try {
    if (!addressForm.value.contactName || 
        !addressForm.value.contactTel || 
        !addressForm.value.address) {
      ElMessage.warning('请填写完整信息');
      return;
    }

    let res;
    if (currentAddress.value) {
      // 编辑现有地址
      const updateData = {
        daId: currentAddress.value.daId,
        contactName: addressForm.value.contactName,
        contactSex: addressForm.value.contactSex,
        contactTel: addressForm.value.contactTel,
        address: addressForm.value.address,
        userId: addressForm.value.userId
      };
      res = await updateAddress(updateData);
    } else {
      // 添加新地址
      res = await addAddress(addressForm.value);
    }

    if (res.code === 0) {
      ElMessage.success(res.message || '保存成功');
      showAddressForm.value = false;
      await loadAddressList();
      resetForm();
    } else {
      ElMessage.error(res.message || '保存失败');
    }
  } catch (error) {
    console.error('保存地址失败:', error);
    ElMessage.error('保存地址失败');
  }
}

// 删除地址
const deleteAddressHandler = async (address) => {
  try {
    const confirmed = await ElMessageBox.confirm(
      '确定要删除该地址吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (confirmed) {
      const res = await deleteAddress(address.daId);

      if (res.code === 0) {
        ElMessage.success(res.message || '删除成功');
        await loadAddressList();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error);
      ElMessage.error('删除地址失败');
    }
  }
}

// 编辑地址
const editAddress = (address) => {
  currentAddress.value = { ...address }; // 创建一个副本
  addressForm.value = {
    daId: address.daId,
    contactName: address.contactName,
    contactSex: address.contactSex,
    contactTel: address.contactTel,
    address: address.address,
    userId: address.userId
  };
  showAddressForm.value = true;
};

// 重置表单
const resetForm = () => {
  currentAddress.value = null;
  addressForm.value = {
    contactName: '',
    contactSex: 1,
    contactTel: '',
    address: '',
    userId: 1 // 需要从登录用户信息中获取
  };
};

// 选择地址
const selectAddress = (address) => {
  // 如果是从支付页面跳转来的
  if (route.query.returnTo === '/payment') {
    router.push({
      path: '/payment',
      query: { 
        orderId: route.query.orderId,
        addressId: address.daId,
        addressName: address.contactName || '',
        addressPhone: address.contactTel || '',
        addressDetail: address.address || ''
      }
    });
  } 
  // 如果是从购物车页面来的
  else if (route.query.from === 'cart') {
    router.push({
      path: '/cart',
      query: {
        addressId: address.daId,
        addressName: address.contactName || '',
        addressPhone: address.contactTel || '',
        addressDetail: address.address || ''
      }
    });
  }
};

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  loadAddressList()
})
</script>

<style scoped>
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3vw 4vw;
  background-color: #ff7043;
  position: sticky;
  top: 0;
  z-index: 1000;
}

header .fa-arrow-left {
  font-size: 4vw;
  color: #fff;
  width: 8vw;
  cursor: pointer;
}

header .title {
  font-size: 4.5vw;
  font-weight: bold;
  color: #fff;
}

header .placeholder {
  width: 8vw;
}

.address-list {
  padding: 2vw 4vw;
}

.address-item {
  background-color: #fff;
  border-radius: 2vw;
  padding: 4vw;
  margin-bottom: 3vw;
  cursor: pointer;
}

.address-item:hover {
  background-color: #f5f5f5;
}

.address-item .user-info {
  margin-bottom: 2vw;
}

.address-item .name {
  font-size: 4vw;
  font-weight: bold;
  margin-right: 3vw;
}

.address-item .phone {
  font-size: 3.5vw;
  color: #666;
  margin-right: 3vw;
}

.address-item .tag {
  font-size: 3vw;
  color: #ee670c;
  border: 1px solid #ee670c;
  padding: 0.5vw 1.5vw;
  border-radius: 3vw;
}

.address-item .address-detail {
  font-size: 3.5vw;
  color: #333;
  line-height: 1.5;
}

.operations {
  display: flex;
  justify-content: flex-end;
  margin-top: 3vw;
  padding-top: 3vw;
  border-top: 1px solid #eee;
}

.operations > div {
  display: flex;
  align-items: center;
  margin-left: 4vw;
  font-size: 3.5vw;
}

.operations i {
  margin-right: 1vw;
}

.operations .edit {
  color: #666;
}

.operations .delete {
  color: #ff4646;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20vw 0;
  color: #999;
}

.empty-state i {
  font-size: 15vw;
  margin-bottom: 3vw;
}

.empty-state p {
  font-size: 4vw;
}

.add-address {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ff7043;
  color: #fff;
  text-align: center;
  padding: 3vw 0;
  font-size: 4vw;
}

/* 弹窗样式调整 */
:deep(.el-dialog) {
  border-radius: 2vw;
}

:deep(.el-dialog__header) {
  padding: 4vw;
  margin-right: 0;
  text-align: center;
  font-size: 4.5vw;
  font-weight: bold;
}

:deep(.el-dialog__body) {
  padding: 4vw;
}

:deep(.el-form-item__label) {
  font-size: 3.8vw;
}

:deep(.el-input__inner) {
  font-size: 3.8vw;
}

:deep(.el-checkbox__label) {
  font-size: 3.8vw;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: bold;
}

.gender {
  font-size: 14px;
  color: #666;
}

.phone {
  font-size: 14px;
  color: #666;
}
</style> 